package edu.school.controller;

import edu.school.utils.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UtilsController {


    @RequestMapping(value="/utils/add.action",method = {RequestMethod.POST})
    @ResponseBody
    public  Map<String,Object>  addBannerAct(HttpServletRequest request, HttpServletResponse response, @RequestParam(value="file",required=false) MultipartFile file)throws Exception {
        String prefix="";
        String dateStr="";
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        String filepath = "";
        String originalName ="";
        try{
            if(file!=null){
                originalName = file.getOriginalFilename();
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                dateStr =  System.currentTimeMillis()/ 1000 + "";
                filepath=WebUtils.getRealPath()+dateStr+"." + prefix;
                //  filepath =/* request.getSession().getServletContext().getRealPath*/("D:\\Program Files\\idea_projects\\student_system\\src\\main\\webapp\\upload\\") +dateStr+"." + prefix;
                /* filepath = filepath.replace("\\", "/");*/
                File files=new File(filepath);
                //打印查看上传路径
                System.out.println(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
            }
        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        Map<String,Object> map2=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","1");
        map.put("data",map2);
        map2.put("src",dateStr+"."+prefix);
        return map;
    }





}
